package com.kun.util;

import cn.hutool.core.io.FileUtil;

import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定义驱动类加载器
 *
 * @author kun.li
 */
public class DriverJarLoader extends URLClassLoader {

    public DriverJarLoader(URL[] urls) {
        this(urls, DriverJarLoader.class.getClassLoader());
    }

    public DriverJarLoader(URL[] urls, ClassLoader parent) {
        super(urls, parent);
        for (URL url : urls) {
            String extName = FileUtil.extName(url.getFile());
            if (!extName.equalsIgnoreCase("jar")) {
                System.out.println("无法加载" + extName + "文件");
            }
        }
    }


    static Map<String, Driver> driverCacheMap = new ConcurrentHashMap<>();


    public static Driver loadDriver(String driverJar,String driverClassName) throws Exception {
        Driver driver = driverCacheMap.get(driverJar);
        if (driver != null) {
            return driver;
        }
        ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
        URL url = new URL(driverJar);
        DriverJarLoader driverJarLoader = new DriverJarLoader(new URL[]{url});
        Thread.currentThread().setContextClassLoader(driverJarLoader);
        Class<?> clazz = driverJarLoader.loadClass(driverClassName);
        driver = (Driver) clazz.getDeclaredConstructor().newInstance();
        Thread.currentThread().setContextClassLoader(oldClassLoader);
        return driver;

    }

    public static void main(String[] args) throws Exception {
        String path = "file:F://jars//mysql-connector-java-8.0.28.jar";
        String driverClassName="com.mysql.cj.jdbc.Driver";
        Driver driver = loadDriver(path,driverClassName);
        System.out.println(driver);
        Properties properties = new Properties();
        properties.setProperty("user","root");
        properties.setProperty("password","root");
        Connection connection = driver.connect("jdbc:mysql:///system_study_model", properties);
        System.out.println(connection);
    }
}
